import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

@ChannelHandler.Sharable
public class MyHeartbeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent IdlEvent = (IdleStateEvent) evt;
            if (IdlEvent.state() == IdleState.READER_IDLE) {
                System.out.println("READER_IDLE");
            }
            else if (IdlEvent.state() == IdleState.WRITER_IDLE) {
                System.out.println("WRITER_IDLE");
            }
            else if (IdlEvent.state() == IdleState.ALL_IDLE) {
                System.out.println("ALL_IDLE");

                ctx.close();
                return;  // TODO: 临时处理
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof MyProtoPackage) {
            MyProtoPackage pack = (MyProtoPackage) msg;
            if (pack.getCommandId() == MyProtoPackage.CMD_PING) {
                pack.setCommandId(MyProtoPackage.CMD_PONG);
                ctx.writeAndFlush(pack);
                return;
            }
        }
        super.channelRead(ctx, msg);
    }


}
